﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Configuration;
using Badhshala.Models;
using Facebook;

namespace Badhshala.Controllers
{
    public class AccountController : BaseController
    {
        public ActionResult Login(string signed_request)
        {
            var fb = FacebookClientHelper.CreateFacebookClient();

            dynamic signedRequest = fb.ParseSignedRequest(fb.AppSecret, signed_request);

            if (signedRequest.user_id != null)
            {
                long fbID = long.Parse(signedRequest.user_id);
                string accessToken = signedRequest.oauth_token;

                fb = FacebookClientHelper.CreateFacebookClient(accessToken);
                dynamic me = fb.Get("me");

                SlotMachineDBEntities ctx = new SlotMachineDBEntities();
                AppUser user = ctx.AppUsers.FirstOrDefault(u => u.FacebookId == fbID);

                if (user == null)
                {
                    user = new AppUser(fbID, me["first_name"], me["last_name"], me["username"]);
                    ctx.AppUsers.AddObject(user);
                    ctx.SaveChanges();
                }

                if (!User.Identity.IsAuthenticated || AccessToken == null)
                {
                    FormsAuthentication.SetAuthCookie(fbID.ToString(), false);
                }

                return RedirectToAction("Jackpot", "Home");
            }
            else
            {
                return Redirect(GetAuthenticationUrl());
            }
        }

        public string GetAuthenticationUrl()
        {
            return string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}",
                GlobalConstants.AppID, HttpUtility.UrlEncode(GlobalConstants.AppUrl));
        }
    }
}
